package com.example.travelsn.db;
//
import static java.lang.Math.abs;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


import java.util.ArrayList;
import java.util.List;

public class DBManager {
    private DBOpenHelper dbOpenHelper;
    private SQLiteDatabase db ;

    public DBManager(Context context) {
        dbOpenHelper = new DBOpenHelper(context,"zjut.db");
        db = dbOpenHelper.getWritableDatabase();
    }
    //用户表操作
    /**
     * add users
     * @param user
     */
    public void addUser(User user){
        ContentValues value = new ContentValues();
        value.put("username",user.getUserName());
        value.put("password",user.getPassword());
        value.put("type",user.getType());
        try{
            db.insert("user",null,value);

        }catch (Exception e){
            System.out.println("Handle addUser exception");
        }finally {
            System.out.println("新建用户成功");
            //db.close();
        }
    }
    //检查用户是否存在
    public boolean checkAlreadyUser(String username){
        User user = new User();
        String sql_queryUser = "select * from user where username= ?";
        Cursor cursor = db.rawQuery(sql_queryUser, new String[] { username });
        //Cursor cursor = db1.query("user",null,"username","username=?",null,null,null);
        if(cursor.getCount() > 0){
            cursor.close();
            return true;
        }
        cursor.close();
        return false;
    }
    //核对用户登录信息
    public boolean checkLoginUser(String username,String password){
        String sql_queryUser = "select password from user where username= ? and password = ?";
        Cursor cursor = db.rawQuery(sql_queryUser, new String[] {username,password});
        //Cursor cursor = db1.query("user",null,"username","username=?",null,null,null);
        if(cursor.moveToFirst() == true){
            cursor.close();
            return true;
        }
        cursor.close();
        return false;
    }
    /**
     * delete user by userName
     * @param userName
     */
    public void deleteUser(String userName){
        try {
            db.delete("user", "username=?", new String[]{userName});
        } catch (Exception e) {
            System.out.println("Handle deleteUser exception");
        } finally {
            System.out.println("Handle deleteUser successful");
        }
    }
    /**
     * glance over all user
     */
    /**
     * 从数据库user表中读取数据
     */
    public List<User> getUsers() {
        List<User> list = new ArrayList<User>();
        Cursor cursor = db.query("user", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                User userInfo = new User();
                userInfo.setUserName(cursor.getString(abs(cursor.getColumnIndex("username"))));
                userInfo.setType(cursor.getInt(abs(cursor.getColumnIndex("type"))));
                list.add(userInfo);
            } while (cursor.moveToNext());
        }
        return list;
    }
    //商家表操作
    /**
     * add seller for system
     * @param seller
     */
    public void addSeller(Seller seller){
        ContentValues value = new ContentValues();
        value.put("sellername",seller.getSellerName());
        value.put("password",seller.getPassword());
        value.put("type",seller.getType());
        try{
            db.insert("seller",null,value);

        }catch (Exception e){
            System.out.println("Handle addSeller exception");
        }finally {
            System.out.println("新建商家成功");
            //db.close();
        }
    }

    /**
     * delete seller by sellerId
     * @param sellerName
     */
    public void deleteSeller(String sellerName){
        try {
            db.delete("seller", "sellername=?", new String[]{sellerName});
        } catch (Exception e) {
            System.out.println("Handle deleteSeller exception");
        } finally {
        }
    }
    //检查用户是否存在
    public boolean checkAlreadySeller(String sellername){
        String sql_querySeller = "select * from seller where sellername= ?";
        Cursor cursor = db.rawQuery(sql_querySeller, new String[] {sellername});
        //Cursor cursor = db1.query("user",null,"username","username=?",null,null,null);
        if(cursor.getCount() > 0){
            cursor.close();
            return true;
        }
        cursor.close();
        return false;
    }
    //核对商家登录信息
    public boolean checkLoginSeller(String sellername,String password){
        User user = new User();
        String sql_queryUser = "select * from seller where sellername= ? and password = ?";
        Cursor cursor = db.rawQuery(sql_queryUser, new String[] {sellername,password});
        //Cursor cursor = db1.query("user",null,"username","username=?",null,null,null);
        if(cursor.moveToFirst() == true){
            cursor.close();
            return true;
        }
        cursor.close();
        return false;
    }
    public void updataSeller(Float latitude,Float longitude,String sellername){
        String sql_updataSeller = "";
        ContentValues value = new ContentValues();
        value.put("latitude",latitude);
        value.put("longitude",longitude);
        db.update("seller",value,"sellername=?",new String[]{sellername});
    }
    public List<Seller> getSeller() {
        List<Seller> list = new ArrayList<Seller>();
        Cursor cursor = db.query("seller", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                Seller userInfo = new Seller();
                userInfo.setSellerName(cursor.getString(abs(cursor.getColumnIndex("sellername"))));
                userInfo.setType(cursor.getInt(abs(cursor.getColumnIndex("type"))));
                list.add(userInfo);
            } while (cursor.moveToNext());
        }
        return list;
    }
    //反馈信息操作
    public void addFeed(Feedback feedback){
        ContentValues value = new ContentValues();
        value.put("content",feedback.getContent());
        value.put("username","anonymous");
        value.put("status","未处理");
        try{
            db.insert("feedback",null,value);
        }catch (Exception e){
            System.out.println("Handle addFeekbacks exception");
        }finally {
            System.out.println("反馈成功");
            //db.close();
        }
    }
    public List<Feedback> getFeedbacks() {
        List<Feedback> list = new ArrayList<Feedback>();
        Cursor cursor = db.query("feedback", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                Feedback feedback = new Feedback();
                feedback.setStatus(cursor.getString(abs(cursor.getColumnIndex("status"))));
                feedback.setContent(cursor.getString(abs(cursor.getColumnIndex("content"))));
                feedback.setUserName(cursor.getString(abs(cursor.getColumnIndex("username"))));
                list.add(feedback);
            } while (cursor.moveToNext());
        }
        return list;
    }
    public void upFeedBack(String username,String content){
        System.out.println(username+"还有"+content);
        ContentValues values=new ContentValues();
        values.put("status","已处理");
        db.update("feedback",values,"username=? and content=?",new String[]{username,content});
        values.clear();
    }
    //商品表操作
    public void addGoods(Good good){
        ContentValues value = new ContentValues();
        value.put("goodsname",good.getGoodsName());
        value.put("goodstype",good.getGoodsType());
        value.put("unitprice",good.getUnitPrice());
        value.put("sellername",good.getSellerName());
        System.out.println("shang品："+good.getGoodsName());
        try{
            db.insert("goods",null,value);

        }catch (Exception e){
            System.out.println("Handle addgood exception");
        }finally {
            System.out.println("新建商品成功");
            //db.close();
        }
    }
    public void deleteGood(String goodsname, String sellername){
        db.delete("goods","goodsname=? and sellername=?",new String[]{goodsname,sellername});
    }
    public List<Good> getGoods(String sellername) {
        List<Good> list = new ArrayList<>();
        System.out.println("正在getGoods");
        Cursor cursor = db.query("goods", null, "sellername = ?", new String[] {sellername},null, null, null);
        if (cursor.moveToFirst()) {
            do {
                Good good = new Good();
                good.setGoodsName(cursor.getString(abs(cursor.getColumnIndex("goodsname"))));
                good.setGoodsType(cursor.getString(abs(cursor.getColumnIndex("goodstype"))));
                good.setUnitPrice(cursor.getFloat(abs(cursor.getColumnIndex("unitprice"))));
                good.setSellerName(cursor.getString(abs(cursor.getColumnIndex("sellername"))));
                list.add(good);
            } while (cursor.moveToNext());
        }
        return list;
    }
    public void upGoods(String goodsname,String sellername,float price){
        System.out.println(goodsname+"还有"+sellername);
        try{
            ContentValues values=new ContentValues();
            values.put("unitprice",price);
            db.update("goods",values,"goodsname=? and sellername=?",new String[]{goodsname,sellername});
            values.clear();
        }catch (Exception e){
            Log.d("exception","update Price faliure");
        }
    }
}
